package org.llw.ldailytask.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.llw.ldailytask.R;
import org.llw.ldailytask.dao.SqliteDao;
import org.llw.ldailytask.entity.Task;
import org.llw.ldailytask.util.CallBack;
import org.llw.ldailytask.util.DateFormatter;
import org.llw.ldailytask.util.LunarCalendar;
import org.llw.ldailytask.util.MyApplication;
import org.llw.ldailytask.util.SlideAdapter;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;

import com.roamer.slidelistview.SlideListView;

public class MainActivity extends FragmentActivity implements OnClickListener,
		OnDateSetListener, OnMenuItemClickListener, CallBack {

	private ImageView imgPreviousMonth, imgNextMonth, imgAddTask,
			imgBackToToday;
	private ViewPager mPager;
	private PagerAdapter mPagerAdapter;
	private DateFormatter formatter;
	private TextView txtTitleGregorian, txtTitleLunar, txtTitleAddition,
			txtTitleMonth, txtToday;
	private View previousCellView;
	private Drawable previousCellViewBG;
	private SlideListView mSlideListView;
	private SlideAdapter mAdapter;
	private List<Task> mTestData;
	private String currentYear, currentMonth, currentDay, today;

	private SqliteDao sqliteDao;
	private List<Task> taskList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
		initCalendarTitle();
		sqliteDao = new SqliteDao(MainActivity.this);
	}

	private void init() {
		// 初始化控件
		imgAddTask = (ImageView) findViewById(R.id.imgAddTask);
		imgNextMonth = (ImageView) findViewById(R.id.imgNextMonth);
		imgPreviousMonth = (ImageView) findViewById(R.id.imgPreviousMonth);
		imgBackToToday = (ImageView) findViewById(R.id.imgBackToToday);
		txtTitleMonth = (TextView) findViewById(R.id.txtMonth);
		txtTitleMonth.setTypeface(MyApplication.myTypeface3);
		txtTitleGregorian = (TextView) findViewById(R.id.txtTitleGregorian);
		txtTitleGregorian.setTypeface(MyApplication.myTypeface3);
		txtTitleLunar = (TextView) findViewById(R.id.txtTitleLunar);
		txtTitleLunar.setTypeface(MyApplication.myTypeface3);
		txtTitleAddition = (TextView) findViewById(R.id.txtAddition);
		txtToday = (TextView) findViewById(R.id.txtToday);
		imgBackToToday.setOnClickListener(this);
		imgAddTask.setOnClickListener(this);
		imgNextMonth.setOnClickListener(this);
		imgPreviousMonth.setOnClickListener(this);
		// 给日期转换器传入资源
		formatter = new DateFormatter(this.getResources());

		// 初始化ViewPager相关
		mPager = (ViewPager) findViewById(R.id.pager);
		mPagerAdapter = new CalendarPagerAdapter(getSupportFragmentManager());
		mPager.setAdapter(mPagerAdapter);
		mPager.setOnPageChangeListener(new simplePageChangeListener());
		mPager.setCurrentItem(getTodayMonthIndex());

		// 初始化TaskListView
		mSlideListView = ((SlideListView) findViewById(R.id.task_list_view));
		mTestData = new ArrayList<Task>();
		randomCreateTestData();
		mAdapter = new SlideAdapter(this, mTestData);
		mSlideListView.setAdapter(mAdapter);
		mSlideListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// String s = (String) parent.getAdapter().getItem(
						// position);
						// if (!TextUtils.isEmpty(s)) {
						// Toast.makeText(MainActivity.this,
						// "OnItemClick:" + s, Toast.LENGTH_SHORT)
						// .show();
						// }

						String taskId = ((TextView) view
								.findViewById(R.id.taskID)).getText()
								.toString();
						String title = ((TextView) view
								.findViewById(R.id.tvTitle)).getText()
								.toString();
						String content = ((TextView) view
								.findViewById(R.id.tvContent)).getText()
								.toString();
						String type = ((TextView) view.findViewById(R.id.type))
								.getText().toString();
						String status = ((TextView) view
								.findViewById(R.id.status)).getText()
								.toString();
						String date = ((TextView) view.findViewById(R.id.date))
								.getText().toString();
						String time = ((TextView) view
								.findViewById(R.id.tvTime)).getText()
								.toString();
						String isalert = ((TextView) view
								.findViewById(R.id.isalert)).getText()
								.toString();

						Bundle b = new Bundle();
						b.putString("id", taskId);
						b.putString("title", title);
						b.putString("content", content);
						b.putString("type", type);
						b.putString("status", status);
						b.putString("date", date);
						b.putString("time", time);
						b.putString("isalert", isalert);
						Intent intent = new Intent(MainActivity.this,
								EditActivity.class);
						intent.putExtras(b);
						
						startActivityForResult(intent, 1);
						//startActivity(intent);

					}
				});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imgAddTask:
			Bundle bundle = new Bundle();
			bundle.putString("currentDate", currentYear + "-" + currentMonth
					+ "-" + currentDay);
			Intent intent = new Intent(MainActivity.this, DetailActivity.class);
			intent.putExtras(bundle);
			// startActivity(intent);
			startActivityForResult(intent, 1);
			break;
		case R.id.imgPreviousMonth:
			mPager.setCurrentItem(mPager.getCurrentItem() - 1);
			break;
		case R.id.imgNextMonth:
			mPager.setCurrentItem(mPager.getCurrentItem() + 1);
			break;
		case R.id.imgBackToToday:
			mPager.setCurrentItem(getTodayMonthIndex());
			break;
		}
	}

	private int getTodayMonthIndex() {
		Calendar today = Calendar.getInstance();
		int offset = (today.get(Calendar.YEAR) - LunarCalendar.getMinYear())
				* 12 + today.get(Calendar.MONTH);
		return offset;
	}

	// 月份显示切换事件
	private class simplePageChangeListener extends
			ViewPager.SimpleOnPageChangeListener {
		@Override
		public void onPageSelected(int position) {
			// set title year month
			StringBuilder title = new StringBuilder();
			title.append(LunarCalendar.getMinYear() + (position / 12));
			// title.append('-');
			int month = (position % 12) + 1;
			// if (month < 10) {
			// title.append('0');
			// }
			// title.append(month);

			// 设置年
			txtTitleGregorian.setText(currentYear = title.toString());
			// 设置月
			txtTitleMonth.setText(getMonth(String.valueOf(month)));
			currentMonth = String.valueOf(month);
			// txtTitleLunar.setText("");
			// set related button's state
			if (position < mPagerAdapter.getCount() - 1
					&& !imgNextMonth.isEnabled()) {
				imgNextMonth.setEnabled(true);
			}
			if (position > 0 && !imgPreviousMonth.isEnabled()) {
				imgPreviousMonth.setEnabled(true);
			}
		}
	}

	// 日期单元格点击事件
	public void onCellClick(View v) {
		if (previousCellView != null) {
			previousCellView.findViewById(R.id.imgCellHint).setBackground(
					previousCellViewBG);
		}
		previousCellView = v;
		previousCellViewBG = v.findViewById(R.id.imgCellHint).getBackground();
		v.findViewById(R.id.imgCellHint).setBackgroundResource(
				R.drawable.img_hint_selected);
		LunarCalendar lc = (LunarCalendar) v.getTag();
		CharSequence[] info = formatter.getFullDateInfo(lc);
		String[] str = info[1].toString().split(" ");
		txtTitleLunar.setText(str[0] + str[1] + str[2] + "   " + str[4]
				+ str[5] + str[6]);
		txtTitleAddition.setText(info[0]);

		Pattern pattern = Pattern.compile("-([0-9]*)-([0-9]*)]");
		Matcher matcher = pattern.matcher(v.getTag().toString());
		while (matcher.find()) {
			currentMonth = String
					.valueOf((Integer.parseInt(matcher.group(1)) + 1));
			currentDay = matcher.group(2);
		}
		setSelectedDay(currentYear, currentMonth, currentDay);

		// Toast.makeText(this, v.getTag().toString(),
		// Toast.LENGTH_SHORT).show();
		// Log.i("cellClick", v.getTag().toString());
	}

	// 日期对话框选择完成事件
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		int offset = (year - LunarCalendar.getMinYear()) * 12 + monthOfYear;
		mPager.setCurrentItem(offset);
	}

	// 日期单元格焦点变化事件
	/*
	 * public void onFocusChange(View v, boolean hasFocus) { //Drawable drawable
	 * = new Drawable(R.drawable.shape_calendar_cell_focused);
	 * v.setBackground(getResources
	 * ().getDrawable(R.drawable.shape_calendar_cell_focused));
	 * 
	 * if (!hasFocus) return; if (flag == 0) { imgAddTask.requestFocus(); flag =
	 * 1; v.setFocusableInTouchMode(true); } else { LunarCalendar lc =
	 * (LunarCalendar) v.getTag(); CharSequence[] info =
	 * formatter.getFullDateInfo(lc); txtTitleLunar.setText(info[1]);
	 * Log.i("cell focus", v.getTag().toString()); }
	 * 
	 * }
	 */

	// 弹出菜单选项点击事件
	@Override
	public boolean onMenuItemClick(MenuItem item) {
		return false;/*
					 * switch (item.getItemId()) { case R.id.menuGoto: int year
					 * = (mPager.getCurrentItem() / 12) +
					 * LunarCalendar.getMinYear(); int month =
					 * mPager.getCurrentItem() % 12; DatePickerDialog dpd = new
					 * DatePickerDialog( this, android.R.style.
					 * Theme_DeviceDefault_DialogWhenLarge_NoActionBar, this,
					 * year, month, 1);
					 * dpd.getDatePicker().setCalendarViewShown(false);
					 * dpd.show(); return true; case R.id.menuAbout:
					 * this.startActivity(new Intent(this,
					 * AboutActivity.class)); return true; default: return
					 * false; }
					 */
	}

	@Override
	public void setToday(LunarCalendar date, String todayDate) {
		today = todayDate;
		currentDay = todayDate.substring(8);
		if (txtTitleLunar.getText().equals("")) {
			LunarCalendar lc = (LunarCalendar) date;
			CharSequence[] info = formatter.getFullDateInfo(lc);
			String[] str = info[1].toString().split(" ");
			txtTitleLunar.setText(str[0] + str[1] + str[2] + "   " + str[4]
					+ str[5] + str[6]);
			txtTitleAddition.setText(info[0]);
			setSelectedDay(currentYear, currentMonth, currentDay);
		}
		System.out.println(todayDate);
	}

	private void randomCreateTestData() {
		mTestData.clear();
		for (int i = 0; i < 1; i++) {
			Task t = new Task();
			t.setContent("这是测试内容有");
			t.setDate("有没有无所谓");
			t.setId(2);
			t.setIsAlert("1");
			t.setStatus("s");
			t.setTime("2015-12-12 12:12:12.000");
			t.setTitle("这是测试标题");
			t.setType("无类型");
			mTestData.add(t);
		}
	}

	private void initCalendarTitle() {
		((TextView) findViewById(R.id.txt_sun))
				.setTypeface(MyApplication.myTypeface2);
		((TextView) findViewById(R.id.txt_mon))
				.setTypeface(MyApplication.myTypeface2);
		((TextView) findViewById(R.id.txt_tue))
				.setTypeface(MyApplication.myTypeface2);
		((TextView) findViewById(R.id.txt_thu))
				.setTypeface(MyApplication.myTypeface2);
		((TextView) findViewById(R.id.txt_wed))
				.setTypeface(MyApplication.myTypeface2);
		((TextView) findViewById(R.id.txt_fri))
				.setTypeface(MyApplication.myTypeface2);
		((TextView) findViewById(R.id.txt_sat))
				.setTypeface(MyApplication.myTypeface2);
	}

	private String getMonth(String str) {
		switch (str) {
		case "1":
			return "Janurary";
		case "2":
			return "February";
		case "3":
			return "March";
		case "4":
			return "April";
		case "5":
			return "May";
		case "6":
			return "June";
		case "7":
			return "July";
		case "8":
			return "August";
		case "9":
			return "September";
		case "10":
			return "October";
		case "11":
			return "November";
		case "12":
			return "December";
		}
		return null;
	}

	private void setSelectedDay(String year, String month, String day) {
		if (day.charAt(0) == '0') {
			day = day.substring(1);
		}
		txtToday.setText(year + "-" + month + "-" + day);
		txtToday.setTypeface(MyApplication.myTypeface3);
		// 查询选中天的task
		taskList = sqliteDao.getDailyTasks(year + "-" + month + "-" + day);

		mSlideListView.setAdapter(new SlideAdapter(this, taskList));
		// mAdapter.setmData(taskList);
		// mAdapter.notifyDataSetChanged();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		setSelectedDay(currentYear, currentMonth, currentDay);
	}

}
